﻿using Sunny.UI;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Dx.Common
{
    public class HttpBaseHelper
    {
        private readonly HttpClient _httpClient;
        public HttpBaseHelper()
        {
            _httpClient = new HttpClient();
        }

        /// <summary>
        /// 有些winform中会调用；比如配合实现进度条
        /// 实现方法如下:
        /// HttpClientHandler handler =  new HttpClientHandler();
        /// ProgressMessageHandler progressMessageHandler = new ProgressMessageHandler(handler);
        /// HttpHelper httpClient = new HttpHelper(progressMessageHandler);
        /// </summary>
        /// <param name="handler"></param>
        public HttpBaseHelper(HttpMessageHandler handler, TimeSpan? timeOut)
        {
            _httpClient = new HttpClient(handler);
            if (timeOut != null)
            {
                _httpClient.Timeout = (TimeSpan)timeOut;
            }
        }

        /// <summary>
        /// get请求
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public async Task<string> GetAsync(string url, Dictionary<string, string> headers)
        {
            try
            {
                headers.ForEach(h =>
                {
                    if (!_httpClient.DefaultRequestHeaders.Contains(h.Key))
                    {
                        _httpClient.DefaultRequestHeaders.Add(h.Key, h.Value);
                    }
                });
                HttpResponseMessage response = await _httpClient.GetAsync(url);
                response.EnsureSuccessStatusCode();
                return await response.Content.ReadAsStringAsync();
            }
            catch (HttpRequestException ex)
            {
                LogHelper.Instance.Error(ex);
                return null;
            }
        }

        public async Task<string> DownFileAsync(string url, Dictionary<string, string> headers, string fileName)
        {
            try
            {
                headers.ForEach(h =>
                {
                    if (!_httpClient.DefaultRequestHeaders.Contains(h.Key))
                    {
                        _httpClient.DefaultRequestHeaders.Add(h.Key, h.Value);
                    }
                });
                HttpResponseMessage response = await _httpClient.GetAsync(url);
                response.EnsureSuccessStatusCode();
                var contentDisposition = response.Content.Headers.ContentDisposition;
                var fileEntension = Path.GetExtension(contentDisposition?.FileName.Trim('"')) ?? Path.GetExtension(url);

                fileName += fileEntension;

                var fileStream = File.Create(fileName);

                await response.Content.CopyToAsync(fileStream);

                fileStream.Close();
            }
            catch (HttpRequestException ex)
            {
                LogHelper.Instance.Error(ex);
            }
            return await Task.FromResult(fileName);
        }

        /// <summary>
        /// post请求
        /// </summary>
        /// <param name="url">链接地址</param>
        /// <param name="data">json对应类数据</param>
        /// <param name="headers">头部信息（token等）</param>
        /// <returns></returns>
        public async Task<string> PostAsync(string url, string data, Dictionary<string, string> headers)
        {
            try
            {
                StringContent content = new StringContent(data, Encoding.UTF8, "application/json");
                headers.ForEach(h =>
                {
                    if (!_httpClient.DefaultRequestHeaders.Contains(h.Key))
                    {
                        _httpClient.DefaultRequestHeaders.Add(h.Key, h.Value);
                    }
                });
                HttpResponseMessage response = await _httpClient.PostAsync(url, content);
                response.EnsureSuccessStatusCode();
                return await response.Content.ReadAsStringAsync();
            }
            catch (HttpRequestException ex)
            {
                // 处理异常
                LogHelper.Instance.Error(ex);
                return null;
            }
        }

        /// <summary>
        /// 多文件上传
        /// </summary>
        /// <param name="url">接口地址</param>
        /// <param name="headers">头部信息</param>
        /// <param name="filePaths">多个文件地址</param>
        /// <param name="paraName">批量上传参数名称比如：files</param>
        /// <returns></returns>
        public async Task<string> UploadFilesAsync(string url, Dictionary<string, string> headers, string[] filePaths, string paraName)
        {
            //使用foreach循环的时候每次迭代完毕之后会关闭所以需要创建一个集合先存起来，最后统一关闭
            List<FileStream> fileStreams = new List<FileStream>();
            try
            {
                //头部信息
                headers.ForEach(h => _httpClient.DefaultRequestHeaders.Add(h.Key, h.Value));

                //文件信息处理
                MultipartFormDataContent multipartFormData = new MultipartFormDataContent();

                filePaths.ForEach(filepath =>
                {
                    var streamContent = new StreamContent(File.OpenRead(filepath));
                    streamContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
                    streamContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data")
                    {
                        Name = paraName,
                        FileName = Path.GetFileName(filepath)
                    };
                    multipartFormData.Add(streamContent);
                });

                HttpResponseMessage response = await _httpClient.PostAsync(url, multipartFormData);
                var Code = response.EnsureSuccessStatusCode();
                return await response.Content.ReadAsStringAsync();
            }
            catch (HttpRequestException ex)
            {
                // 处理异常
                LogHelper.Instance.Error(ex);
                return ex.Message;
            }
            finally
            {
                fileStreams.ForEach(stream => stream.Close());
            }
        }

        /// <summary>
        /// 多文件上传
        /// </summary>
        /// <param name="url">接口地址</param>
        /// <param name="headers">头部信息</param>
        /// <param name="streamDics">多个流字典</param>
        /// <param name="paraName">批量上传参数名称比如：files</param>
        /// <returns></returns>
        public async Task<string> UploadFilesAsync(string url, Dictionary<string, string> headers, Dictionary<string, Stream> streamDics, string paraName)
        {
            //使用foreach循环的时候每次迭代完毕之后会关闭所以需要创建一个集合先存起来，最后统一关闭
            List<FileStream> fileStreams = new List<FileStream>();
            try
            {
                //头部信息
                headers.ForEach(h => _httpClient.DefaultRequestHeaders.Add(h.Key, h.Value));

                //文件信息处理
                MultipartFormDataContent multipartFormData = new MultipartFormDataContent();

                streamDics.ForEach(dic =>
                {
                    var streamContent = new StreamContent(dic.Value);
                    streamContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
                    streamContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data")
                    {
                        Name = paraName,
                        FileName = dic.Key
                    };
                    multipartFormData.Add(streamContent);
                });

                HttpResponseMessage response = await _httpClient.PostAsync(url, multipartFormData);
                var Code = response.EnsureSuccessStatusCode();
                return await response.Content.ReadAsStringAsync();
            }
            catch (HttpRequestException ex)
            {
                // 处理异常
                LogHelper.Instance.Error(ex);
                return ex.Message;
            }
            finally
            {
                fileStreams.ForEach(stream => stream.Close());
            }
        }

        /// <summary>
        /// 保存文件到本地
        /// </summary>
        /// <param name="url">链接地址</param>
        /// <param name="headers">头部信息</param>
        /// <param name="data">json对应类数据</param>
        /// <param name="fileName">文件名称</param>
        public async void SaveFileAsync(string url, Dictionary<string, string> headers, string data, string fileName)
        {
            try
            {
                StringContent content = new StringContent(data, Encoding.UTF8, "application/json");
                headers.ForEach(h =>
                {
                    _httpClient.DefaultRequestHeaders.Add(h.Key, h.Value);
                });
                HttpResponseMessage response = await _httpClient.PostAsync(url, content);
                response.EnsureSuccessStatusCode();

                // 读取响应内容
                using (Stream contentStream = await response.Content.ReadAsStreamAsync())
                {
                    // 将内容保存到文件
                    using (FileStream fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write))
                    {
                        await contentStream.CopyToAsync(fileStream);
                        MessageBox.Show("文件下载完成！");
                    }
                }
            }
            catch (HttpRequestException ex)
            {
                // 处理异常
                LogHelper.Instance.Error(ex);
            }
        }
    }
}
